package com.xhj.springbootproject.config;

import com.xhj.springbootproject.constant.ResultCodeEnum;
import com.xhj.springbootproject.service.intf.SendMailService;
import com.xhj.springbootproject.util.JsonResult;
import com.xhj.springbootproject.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Xionghaijun
 * @date ：Created in 2019/7/2 5:39 PM
 * @description： 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandle {

    @Value("${spring.mail.send.to}")
    private String sendTo;

    @Value("${spring.project.name}")
    private String projectName;

    @Autowired
    private SendMailService sendMailService;

//    @Autowired
//    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private TemplateEngine templateEngine;

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ModelAndView handleException(HttpServletRequest request, Exception e){
        logger.error("全局异常处理获取程序运行出错信息，错误信息 {}", e);
        String content = "";
        try {
            // 获取模版对象
//            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("/email/emailTemplate.ftl");
//
//            // 准备的 model data
//            Map<String, String> map = new HashMap<>();
//            map.put("project", projectName);
//            map.put("time", TimeUtil.date());
//            map.put("errorMessage", e.toString());
//
//            // 解析 模版和 数据
//            content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            // 准备的 model data
            Map<String, Object> map = new HashMap<>();
            map.put("project", projectName);
            map.put("time", TimeUtil.date());
            map.put("errorMessage", e.toString());
            Context context = new Context();
            context.setVariables(map);
            content = this.templateEngine.process("/email/email", context);
        } catch (Exception exc) {
            logger.error("全局异常处理中，发送html邮件出错，出错信息 = {}", exc);
        }
        sendMailService.sendHtmlMail(sendTo, projectName + "项目报错提醒", content);
        ModelAndView mav = new ModelAndView("error"); // 设置跳转路径
        mav.addObject("exception", e); // 将异常对象传递过去
        mav.addObject("url", request.getRequestURL()); // 获得请求的路径
        return mav;
    }

}
